/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.erp.prod.bom.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.hibernate.exception.ConstraintViolationException;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.springmvc.ControllerSupport;
import org.redragon.framework.util.ShiroUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.erp.dataset.service.DatasetCommonService;
import com.erp.hr.dao.model.HrStaffInfoRO;
import com.erp.hr.service.HrCommonService;
import com.erp.masterdata.common.service.MasterDataCommonService;
import com.erp.masterdata.material.dao.data.DataBox;
import com.erp.masterdata.material.dao.model.MdMaterial;
import com.erp.prod.bom.dao.model.ProdBomHead;
import com.erp.prod.bom.dao.model.ProdBomHeadCO;
import com.erp.prod.bom.dao.model.ProdBomLine;
import com.erp.prod.bom.dao.model.ProdBomLineCO;
import com.erp.prod.bom.service.ProdBomHeadService;
import com.erp.prod.bom.service.ProdBomLineService;

@Controller
@RequestMapping("/web/prodBomHead")
public class ProdBomHeadWebController extends ControllerSupport{
    
    //日志处理
    private Logger logger = LoggerFactory.getLogger(ProdBomHeadWebController.class);
    
    //服务层注入
    @Autowired
    private ProdBomHeadService prodBomHeadService;
    @Autowired
    private ProdBomLineService prodBomLineService;
    @Autowired
    private MasterDataCommonService masterDataCommonService;
    @Autowired
    private DatasetCommonService datasetCommonService;
    @Autowired
    private HrCommonService hrCommonService;
    
    @Override
    public String getExceptionRedirectUrl() {
        return this.getFormatRedirectUrl("getProdBomHeadList");
    }
    
    
    
    /**
     * 
     * @description 查询数据列表
     * @date 2020-11-13 16:07:19
     * @author 
     * @param pages
     * @param prodBomHeadCO
     * @param model
     * @return String
     *
     */
    @RequestMapping("getProdBomHeadList")
    public String getProdBomHeadList(Pages pages, ProdBomHeadCO prodBomHeadCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        
        //分页查询数据
        List<ProdBomHead> prodBomHeadList = this.prodBomHeadService.getDataObjectsForDataAuth("", pages, prodBomHeadCO);
        
        //物料Map
        Map<String, String> materialMap = this.masterDataCommonService.getMaterialForMaterialMap();
        
        //循环获取物料信息
        for(ProdBomHead prodBomHead: prodBomHeadList) {
            MdMaterial mdMaterial = this.masterDataCommonService.getMdMaterialInfoCache(prodBomHead.getMaterialCode());
            prodBomHead.setMaterialUnit(this.datasetCommonService.getMaterialUnit().get(mdMaterial.getMaterialUnit()));
            prodBomHead.setMaterialStandard(mdMaterial.getStandard());
        }
        
        //页面属性设置
        model.addAttribute("prodBomHeadList", prodBomHeadList);
        model.addAttribute("pages", pages);
        model.addAttribute("materialMap", materialMap);
        
        return "basic.jsp?content=prodBom/prodBomList";
    }
    
    
    
    /**
     * 
     * @description 查询单条数据
     * @date 2020-11-13 16:07:19
     * @author 
     * @param prodBomHead
     * @param model
     * @return String
     *
     */
    @RequestMapping("getProdBomHead")
    public String getProdBomHead(ProdBomHead prodBomHead, Model model) {
        //查询要编辑的数据
        if(prodBomHead!=null&&StringUtils.isNotBlank(prodBomHead.getBomHeadCode())) {
            ProdBomHead prodBomHeadTemp = this.prodBomHeadService.getDataObject(prodBomHead.getBomHeadCode());
            if(prodBomHeadTemp!=null) {
                prodBomHead = prodBomHeadTemp;
            }
            
            //获取物料信息
            MdMaterial mdMaterial = this.masterDataCommonService.getMdMaterialInfoCache(prodBomHead.getMaterialCode());
            prodBomHead.setMaterialUnit(this.datasetCommonService.getMaterialUnit().get(mdMaterial.getMaterialUnit()));
            prodBomHead.setMaterialStandard(mdMaterial.getStandard());
            
            //设置显示字段
            prodBomHead.setStaffName(this.hrCommonService.getHrStaff(prodBomHead.getStaffCode()).getStaffName());
            prodBomHead.setDepartmentName(this.hrCommonService.getHrDepartment(prodBomHead.getDepartmentCode()).getDepartmentName());
        }else {
            //获取当前用户职员信息
            HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
            prodBomHead.setStaffCode(staffInfo.getStaffCode());
            prodBomHead.setDepartmentCode(staffInfo.getDepartmentCode());
            prodBomHead.setStaffName(staffInfo.getStaffName());
            prodBomHead.setDepartmentName(staffInfo.getDepartmentName());
        }
        
        //物料Map
        Map<String, String> materialMap = this.masterDataCommonService.getMaterialForMaterialMap();
        
        //页面属性设置
        model.addAttribute("prodBomHead", prodBomHead);
        model.addAttribute("materialMap", materialMap);
        
        return "basic.jsp?content=prodBom/prodBomEdit";
    }
    
    
    
    /**
     * 
     * @description 获取bom物料信息
     * @date 2020年11月15日
     * @author dongbin
     * @param materialCode
     * @return
     * @return String
     *
     */
    @RequestMapping("getBomMaterialInfoAjax")
    @ResponseBody
    public String getBomMaterialInfoAjax(String materialCode) {
        String materialUnit = "";
        String materialStandard = "";
        String materialUnitCode = "";
        
        try {
            //获取物料信息
            MdMaterial mdMaterial = this.masterDataCommonService.getMdMaterialInfoCache(materialCode);
            
            materialUnit = this.datasetCommonService.getMaterialUnit().get(mdMaterial.getMaterialUnit());
            materialStandard = mdMaterial.getStandard();
            materialUnitCode = mdMaterial.getMaterialUnit();
        }catch(Exception e) {
            
        }
        
        return "{\"materialUnit\": \""+materialUnit+"\", \"materialUnitCode\": \""+materialUnitCode+"\", \"materialStandard\":\""+materialStandard+"\"}";
    }
    
    
    
    /**
     * 
     * @description 编辑数据
     * @date 2020-11-13 16:07:19
     * @author 
     * @param prodBomHead
     * @param bindingResult
     * @param model
     * @return String
     *
     */
    @RequestMapping("editProdBomHead")
    public String editProdBomHead(@Valid ProdBomHead prodBomHead, BindingResult bindingResult, Model model, RedirectAttributes attr) {
        //参数校验
        Map<String, String> errorMap = this.validateParameters(bindingResult, model);
        if(errorMap.size()>0) {
            return "forward:getProdBomHead";
        }
        
        try {
            //对当前编辑的对象初始化默认的字段
            
            //保存编辑的数据
            this.prodBomHeadService.insertOrUpdateDataObject(prodBomHead);
        }catch(Exception e) {
            if(e.getCause().getCause().getMessage().contains("material_code_UNIQUE")) {
                //提示信息
                model.addAttribute("hint", "hint");
                model.addAttribute("alertMessage", "当前物料已创建物料清单，无法重复创建");                
                return "forward:getProdBomHead";
            }else if(e.getCause().getClass()==ConstraintViolationException.class) {
                //提示信息
                attr.addFlashAttribute("hint", "hint");
                attr.addFlashAttribute("alertMessage", "物料清单编码已存在，请重新输入");
                return "redirect:getProdBomHeadList";
            }else {
                throw e;
            }
        }
        
        //提示信息
        attr.addFlashAttribute("hint", "success");
        attr.addAttribute("bomHeadCode", prodBomHead.getBomHeadCode());
        
        return "redirect:getProdBomHead";
    }
    
    
    
    /**
     * 
     * @description 删除数据
     * @date 2020-11-13 16:07:19
     * @author 
     * @param prodBomHead
     * @return String
     *
     */
    @RequestMapping("deleteProdBomHead")
    public String deleteProdBomHead(ProdBomHead prodBomHead, RedirectAttributes attr) {
        //删除数据前验证数据
        if(prodBomHead!=null&&prodBomHead.getBomHeadId()!=null&&StringUtils.isNotBlank(prodBomHead.getBomHeadCode())) {
            int lineCount = this.prodBomLineService.getBomLineCountByBomHeadCode(prodBomHead.getBomHeadCode());
            
            if(lineCount==0) {
                //删除数据
                this.prodBomHeadService.deleteDataObject(prodBomHead);
                //提示信息
                attr.addFlashAttribute("hint", "success");
            }else {
                //提示信息
                attr.addFlashAttribute("hint", "hint");
                attr.addFlashAttribute("alertMessage", "物料清单存在行，无法删除");
            }
        }
        
        return "redirect:getProdBomHeadList";
    }
    
    
    
    /**
     * 
     * @description 调转多级BOM页面
     * @date 2020年11月15日
     * @author dongbin
     * @param bomHeadCode
     * @param model
     * @return
     * @return String
     *
     */
    @RequestMapping("getBomTree")
    public String getBomTree(String bomHeadCode, Model model, RedirectAttributes attr) {
        //获取bom头
        ProdBomHead prodBomHead = this.prodBomHeadService.getDataObject(bomHeadCode);
        
        //验证bom避免死循环
        if(prodBomHead!=null) {
            Map<String, String> materialMapTemp = new HashMap<String, String>();
            Map<String, String> validateResultMap = new HashMap<String, String>();
            validateResultMap.put("validateResult", "");
            String validateResult = this.prodBomHeadService.validateBom(materialMapTemp, prodBomHead.getMaterialCode(), "", validateResultMap);
            if(StringUtils.isNotBlank(validateResult)) {
                //提示信息
                attr.addFlashAttribute("hint", "hint");
                attr.addFlashAttribute("alertMessage", validateResult);
                return "redirect:getProdBomHeadList";
            }
        }
        
        return "basic.jsp?content=prodBom/prodBomTree";
    }
    
    
    
    /**
     * 
     * @description 获取bom树结构
     * @date 2020年11月15日
     * @author dongbin
     * @param bomHeadCode
     * @return
     * @return String
     *
     */
    @RequestMapping("getBomTreeHtml")
    @ResponseBody
    public String getBomTreeHtml(String bomHeadCode) {
        //物料Map
        Map<String, String> materialMap = this.masterDataCommonService.getMaterialForMaterialMap();
        
        //获取bom头
        ProdBomHead prodBomHead = this.prodBomHeadService.getDataObject(bomHeadCode);
        
        //获取bom行
        //分页查询数据
        Pages pages = new Pages();
        pages.setPage(1);
        pages.setMax(100);
        ProdBomLineCO prodBomLineCO = new ProdBomLineCO();
        prodBomLineCO.setBomHeadCode(bomHeadCode);
        
        List<ProdBomLine> prodBomLineList = this.prodBomLineService.getBomLineListByBomHeadCode(pages, prodBomLineCO);
        
        //跟节点
        StringBuffer html = new StringBuffer("<ol class='dd-list'><li class='dd-item' data-id='"+prodBomHead.getBomHeadId()+"'>"
                                           + "<div class='dd-handle'> "+prodBomHead.getMaterialCode()+" "+materialMap.get(prodBomHead.getMaterialCode())
                                           + " <div style='float: right;'><a href='web/prodBomHead/getProdBomHead?bomHeadCode="+prodBomHead.getBomHeadCode()+"'>编辑当前行BOM</a>&nbsp;&nbsp;</div></div>");
        
        if(prodBomLineList!=null&&prodBomLineList.size()>0) {
            html.append("<ol class='dd-list'>");
            //循环行
            for(ProdBomLine prodBomLine: prodBomLineList) {
                //获取物料信息
                MdMaterial mdMaterial = this.masterDataCommonService.getMdMaterialInfoCache(prodBomLine.getMaterialCode());
                
                html.append("<li class='dd-item' data-id='"+prodBomLine.getBomLineId()+"'>"
                          + "<div class='dd-handle'>[序号"+prodBomLine.getOrderNumber()+"#"+DataBox.getBomPropertyMap().get(mdMaterial.getBomProperty())+"] "+prodBomLine.getMaterialCode()+" "+materialMap.get(prodBomLine.getMaterialCode())+" -- (数量"+prodBomLine.getQuantity()+")");
                String[] childTree = this.getBomChildTree(prodBomLine.getMaterialCode());
                String bomHeadCodeTemp = childTree[0];
                String childHtml = childTree[1];
                if(!childHtml.equals("")) {
                    html.append(" <div style='float: right;'><a href='web/prodBomHead/getProdBomHead?bomHeadCode="+bomHeadCodeTemp+"'>编辑当前行BOM</a>&nbsp;&nbsp;</div>");
                }
                html.append("</div>");
                html.append(childHtml);
                html.append("</li>");
            }
            html.append("</ol>");
        }
        
        html.append("</li></ol>");
        
        return html.toString();
    }
    //获取子树的结构
    private String[] getBomChildTree(String materialCode) {
      //根据物料获取bom头
        ProdBomHead prodBomHead = this.prodBomHeadService.getProdBomHeadByMaterialCode(materialCode);
        if(prodBomHead!=null) {
            //获取bom行
            //分页查询数据
            Pages pages = new Pages();
            pages.setPage(1);
            pages.setMax(100);
            ProdBomLineCO prodBomLineCO = new ProdBomLineCO();
            prodBomLineCO.setBomHeadCode(prodBomHead.getBomHeadCode());
            
            List<ProdBomLine> prodBomLineList = this.prodBomLineService.getBomLineListByBomHeadCode(pages, prodBomLineCO);
            
            //物料Map
            Map<String, String> materialMap = this.masterDataCommonService.getMaterialForMaterialMap();
            
            if(prodBomLineList!=null&&prodBomLineList.size()>0) {
                StringBuffer html = new StringBuffer("<ol class='dd-list'>");
                
                for(ProdBomLine prodBomLine: prodBomLineList) {
                    //获取物料信息
                    MdMaterial mdMaterial = this.masterDataCommonService.getMdMaterialInfoCache(prodBomLine.getMaterialCode());
                    
                    html.append("<li class='dd-item' data-id='"+prodBomLine.getBomLineId()+"'><div class='dd-handle'>[序号"+prodBomLine.getOrderNumber()+"#"+DataBox.getBomPropertyMap().get(mdMaterial.getBomProperty())+"] "+prodBomLine.getMaterialCode()+" "+materialMap.get(prodBomLine.getMaterialCode())+" -- (数量"+prodBomLine.getQuantity()+")");
                    String[] childTree = this.getBomChildTree(prodBomLine.getMaterialCode());
                    String bomHeadCodeTemp = childTree[0];
                    String childHtml = childTree[1];
                    if(!childHtml.equals("")) {
                        html.append(" <div style='float: right;'><a href='web/prodBomHead/getProdBomHead?bomHeadCode="+bomHeadCodeTemp+"'>编辑当前行BOM</a>&nbsp;&nbsp;</div>");
                    }
                    html.append("</div>");
                    html.append(childHtml);
                    html.append("</li>");
                }
                
                html.append("</ol>");
                
                return new String[] {prodBomHead.getBomHeadCode(), html.toString()};
            }
        }
        
        return new String[] {"", ""};
    }

}
